import httplib
import MySQLdb
import sys
#http://quote.stock.hexun.com/stockdata/stock_quote.aspx?stocklist=002628

def getCurrentPrice(stockcode):
  conn = httplib.HTTPConnection("quote.stock.hexun.com")
  conn.request("GET", "/stockdata/stock_quote.aspx?stocklist=%s" % (stockcode))
  r1 = conn.getresponse()
  data = r1.read()
  data=data.decode('gb18030')
  pos1=data.find("[[")
  pos2=data.find("]]", pos1)
  data=data[pos1+2:pos2]
  seq=data.split(",")
  if len(seq) < 4:
    return None 
  return [seq[2], seq[3]]

#print getCurrentPrice("300074")
#sys.exit()

f=open("stocks")
lines=f.readlines()
conn=MySQLdb.connect(host="10.241.84.65",user="root",db="stock")
cursor = conn.cursor()
c=0
for i in lines:
  seq = i.strip().split()
  res=getCurrentPrice(seq[0])
  if not res:
    continue
  sql = "insert into stock_info(code, curprice,curwave) values('%s', %s,%s) on duplicate key update curprice=values(curprice),curwave=values(curwave)" % (seq[0], res[0], res[1]);
  #if seq[0]=='300074':
  #  print sql
  cursor.execute(sql)
  c+=1
  print c

